//
//  LecturerViewController.swift
//  jiahui
//
//  Created by 3tee on 2024/12/6.
//

import UIKit
import avd_sdk
import RxSwift
import SnapKit
import RxCocoa

class LecturerViewController: UIViewController {

    lazy var msgs = [MessageModel]()
    
    lazy var danmuLab: UILabel = {
        let lab = UILabel()
        lab.text = ""
        
        lab.font = .systemFont(ofSize: 13)
        lab.textColor = .red
        return lab
    }()
    lazy var tfootView: UIView = {
        let footV = UIView()
        footV.backgroundColor = .systemGray6
        footV.alpha = 0.6
        footV.layer.cornerRadius = 10
        footV.layer.masksToBounds = true
        return footV
    }()
    
    lazy var inputTf: UITextField = {
        let inputTF = UITextField()
        inputTF.textColor = .white
        inputTF.placeholder = "输入聊天消息"
        inputTF.font = .systemFont(ofSize: 13)
        return inputTF
    }()
    
    lazy var msgTableview: UITableView = {
        $0.dataSource = self
        $0.delegate = self
        $0.backgroundColor = .clear
        $0.layer.cornerRadius = 5
        $0.layer.masksToBounds = true
        $0.alpha = 0.5
        return $0
    }(UITableView(frame: CGRectZero, style: .plain))
    
    lazy var selfRender:AVDVideoView = {
        $0.layer.borderWidth = 0.5
        $0.layer.borderColor = UIColor.white.cgColor
        $0.layer.cornerRadius = 8
        $0.layer.masksToBounds = true
        return $0
    }(AVDVideoView())
    
    @IBOutlet weak var lecturerRender: AVDVideoView!
    lazy var bag = DisposeBag()
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let parentVC: MeetingViewController =  self.parent?.parent as! MeetingViewController
        print("当前按钮状态 = \(parentVC.videoBtn.isSelected)")
        if parentVC.videoBtn.isSelected {
            ThreeTManager.shardInstance.openCamera(true)
        }
        if parentVC.audioBtn.isSelected {
            ThreeTManager.shardInstance.openMic(isOpen: true)
        }
        
        msgs = DBManager.shared.getMsgs(cls: MessageModel.self) ?? []
        print("数据库查询聊天记录成功 = \(msgs.count)")
        msgTableview.reloadData()
        
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("type = \(type(of: lecturerRender))")
        view.addSubview(selfRender)
        view.addSubview(msgTableview)
        view.addSubview(tfootView)
        tfootView.addSubview(inputTf)
        view.addSubview(danmuLab)
        
        selfRender.snp.makeConstraints { make in
            make.right.equalTo(-15)
            make.bottom.equalTo(0)
            make.width.equalTo(140)
            make.height.equalTo(230)
        }
        msgTableview.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.bottom.equalTo(tfootView.snp.top)
            make.height.equalTo(200)
            make.width.equalTo(200)
        }
        tfootView.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.width.equalTo(200)
            make.bottom.equalTo(0)
            make.height.equalTo(44)
        }
        
        inputTf.snp.makeConstraints { make in
            make.left.right.bottom.top.equalTo(0)
        }
        
        danmuLab.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.bottom.equalTo(tfootView.snp.bottom)
           
        }
        
        msgTableview.register(UITableViewCell.self, forCellReuseIdentifier: "xxx")
        
        let aftertime: DispatchTimeInterval = .seconds(2)
        let deadline = DispatchTime.now() + aftertime
        ThreeTManager.shardInstance.cameraOpenNoti.subscribe {[weak self] deviceid in
            guard let strongself = self else { return }
            print("主讲人模式摄像头打开 id = \(deviceid)")
            strongself.lecturerRender.setVideoId(deviceid)
            ThreeTManager.shardInstance.attachRender(strongself.lecturerRender)
        }.disposed(by: bag)

        
        ThreeTManager.shardInstance.cameraCloseNoti.subscribe {[weak self] deviceid in
            guard let strongself = self else { return }
            print("主讲人模式监听到摄像头关闭 id = \(deviceid)")
            if strongself.lecturerRender.getVideoId() != ""{
                print("主讲人renderid = \(strongself.lecturerRender.getVideoId())")
                ThreeTManager.shardInstance.detachRender(strongself.lecturerRender)
            }
        }.disposed(by: bag)
        
        ThreeTManager.shardInstance.localCameraOpenNoti.subscribe {[weak self]  deviceid in
            guard let strongself = self else { return }
            strongself.selfRender.setVideoId(deviceid)
            ThreeTManager.shardInstance.attachRender(strongself.selfRender)

        }.disposed(by: bag)
        
        ThreeTManager.shardInstance.localCameraCloseNoti.subscribe {[weak self] deviceid in
            guard let strongself = self else { return }
            ThreeTManager.shardInstance.detachRender(strongself.selfRender)

        }.disposed(by: bag)
        
        inputTf.rx.controlEvent(.editingDidEndOnExit).subscribe {[weak self] _ in
            guard let strongself = self else { return }
            if let text = strongself.inputTf.text{
                strongself.inputTf.text = ""
               // let msg = AVDMessage(fromId: "capybara", fromName: "👦", message: text)
                let model = MessageModel()
                model.content = text
                model.fromName = "capybara"
                model.userid = "capybara"
                model.msgTime = Int64(NSDate().timeIntervalSince1970)
                model.key = model.userid + String(describing: model.msgTime)
                ThreeTManager.shardInstance.sendMsg(text)
                strongself.reload(model)
            }
        }.disposed(by: bag)
        
        ThreeTManager.shardInstance.msgReceiveNoti.subscribe {[weak self] avdmsg in
            guard let self = self else {return}
            if let msg = avdmsg.element {
                let model = MessageModel()
                model.content = msg.message
                model.userid = msg.fromId
                model.fromName = msg.fromName
                model.msgTime = Int64(NSDate().timeIntervalSince1970)
                model.key = model.userid + String(describing: model.msgTime)
                self.reload(model)
            }
            
        }.disposed(by: bag)
        
        // Do any additional setup after loading the view.
    }
    
    func reload(_ msg: MessageModel) {
        msgs.append(msg)
        msgTableview.reloadData()
        let lastIndexPath = IndexPath(row: msgs.count - 1, section: 0)
        UIView.animate(withDuration: 0.25) {
            self.msgTableview.scrollToRow(at: lastIndexPath, at:.bottom, animated: true)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
            UIView.animate(withDuration: 1) {
            }
        })
//        self.danmuLab.text = msg
//        let duration = 40 / 100.0
//        UIView.animate(withDuration: 1 + duration, delay: 0,options: [.allowAnimatedContent]) {
//            self.danmuLab.alpha = 0
//            self.danmuLab.frame.origin.y += 66
//        } completion: { _ in
//            //self.danmuLab.removeFromSuperview()
////            self.danmuLab.snp.updateConstraints { make in
////                make.bottom.equalTo(self.tfootView.snp.bottom)
////            }
////            self.danmuLab.alpha = 1;
//        }

    }

}

extension LecturerViewController{
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
       
    }
}

extension LecturerViewController: UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return msgs.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "xxx") as! UITableViewCell
        cell.backgroundColor = .clear
        let msg = msgs[indexPath.row]
        cell.textLabel?.textColor = .white
        let nameAtt = NSMutableAttributedString(string: msg.fromName)
        let redRange = (msg.fromName as NSString).range(of: msg.fromName)
        nameAtt.addAttribute(.foregroundColor, value: UIColor.orange, range: redRange)
        nameAtt.append(NSAttributedString(string: ":" + msg.content))
        cell.textLabel?.attributedText = nameAtt
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
}
